import Button from "components/items/button";
import { getUser, cloudStorage } from "common/jscloud";
import allFilds from "common/filds";
import createTable, {reloadTableData} from './table'
import copyright from "../../copyright"

const {lib} = ao2
const {nav} = Pager
const PAGE_HOOKS = lib.hooks('GLOBAL-PAGE')  // 全局page变量


export default function(Pager, options){
  let COLLECTION_NAME = options.collectionName
  let TABLE_COLUMNS_NAME = options.columnsName
  let collectionTitle = options.collectionTitle
  let events = options.events
  let myTemplate = options.template
  
  let COLLECTIONS = cloudStorage(COLLECTION_NAME)  // 创建云集合，如果该集合不存在则创建，如果该集合存在则不处理
  ao2.CLOUD_COLLECTION = COLLECTIONS

  return Pager({
    data: {
      tipsList: [],
      tableInit: false
    },

    // 在未获得用户信息时，暂存其他方法
    __afterGetUserInfo: [],

    async onLoad(param){
      try {
        const that = this
        const userState = PAGE_HOOKS.getItem('user')  // 获取用户数据
        this.cloudCollection = COLLECTIONS
        
        const bt = await createTable.call(this, {
          tableColumnsName: TABLE_COLUMNS_NAME,
          collectionName: COLLECTION_NAME,
          events
        })
        this.bt = bt
        this.tableColumns = bt.__tableColumns
  
        this.setData({ tableInit: true }, async function() {
          const table = await bt.getBootstrapTable();
          table.bootstrapTable('showLoading')
          
          if (!userState) {
            const user = await getUser();
            PAGE_HOOKS.setItem('user', user)
          }
  
          if (that.__afterGetUserInfo.length) {
            if (that.tableColumns) {
              that.__afterGetUserInfo.forEach(cb=>cb.call(that, table))
              that.__afterGetUserInfo = []
            } else {
              throw new Error('未取得该集合的表头信息，请确认该集合是否存在')
            }
          }
        })
      } catch (error) {
        console.error(error);
      }
    },

    async onReady(){
      const userState = PAGE_HOOKS.getItem('user')  // 获取用户数据
      if (!userState) {
        this.__afterGetUserInfo.push(reloadTableData)
      } else {
        this.__afterGetUserInfo.push(function() {
          reloadTableData.call(this, null, 'init')    // 第二次进入该页面
        })
      }
    },

    onAdd() {
      let row = {}
      row.collectionName = TABLE_COLUMNS_NAME  // 指定使用的字段
      row.columnsName = TABLE_COLUMNS_NAME  // 指定使用的字段
      row.columnsFilds = JSON.stringify(this.tableColumns)
      nav.redirectTo({
        url: '/order/detail',
        data: row,
        beforeNav(to, from, next) {
          next()
        }
      })
    }, 

    template(state, props) {
      const bootstrapTable = state.tableInit ? this.bt : null
      let  tableUI = null
      if (bootstrapTable) tableUI = <bootstrapTable.UI />
      if (lib.isFunction(myTemplate)) {
        return myTemplate.call(this, state, props, tableUI)
      }
      return (
        <>
          <View className='ss-card pages-title-lg'>{(collectionTitle||'没有输入标题')}</View>
          <View className='ss-card m-default'>
            <View className='row-flex'>
              <Button title='添加' itemClass='btn-default' tap={this['onAdd']} />
              <Button title='删除' itemClass='btn-default ml-default' tap={this['onAdd']} />
            </View>
            {tableUI}
          </View>
          <copyright.UI />
        </>
      )
    }

  })

}
